package cn.wen.mybatis.framework.executor;


import cn.wen.mybatis.framework.reflection.MetaObject;
import cn.wen.mybatis.framework.reflection.factory.ObjectFactory;
import cn.wen.mybatis.framework.session.Configuration;

import java.lang.reflect.Array;
import java.util.List;

/**
 * ResultExtractor负责将延迟加载得到的对象转换成用户配置的targetType的类型，
 * 核心方法为extractObjectFromList。
 */
public class ResultExtractor {

  private final Configuration configuration;
  private final ObjectFactory objectFactory;

  public ResultExtractor(Configuration configuration, ObjectFactory objectFactory) {
    this.configuration = configuration;
    this.objectFactory = objectFactory;
  }

  /**
   * 主要方法
   * @param list
   * @param targetType
   * @return
   */
  public Object extractObjectFromList(List<Object> list, Class<?> targetType) {
    Object value = null;
    // 如果targetType本来就是集合类型，则无需转换
    if (targetType != null && targetType.isAssignableFrom(list.getClass())) {
      value = list;
      //如果是Collection接口的子类，可以是list，也可以是set
    } else if (targetType != null && objectFactory.isCollection(targetType)) {
      // 转换为ArrayList类型
      value = objectFactory.create(targetType);
      MetaObject metaObject = configuration.newMetaObject(value);
      metaObject.addAll(list);
      // 如果是数组
    } else if (targetType != null && targetType.isArray()) {
      // 判断其数组中元素的类型
      Class<?> arrayComponentType = targetType.getComponentType();
      Object array = Array.newInstance(arrayComponentType, list.size());
      if (arrayComponentType.isPrimitive()) { // 如果是基本类型
        for (int i = 0; i < list.size(); i++) {
          Array.set(array, i, list.get(i));
        }
        value = array;
      } else {  // 如果是包装类型则将其转为Object[]
        value = list.toArray((Object[])array);
      }
    } else {
      if (list != null && list.size() > 1) {
        throw new ExecutorException("Statement returned more than one row, where no more than one was expected.");
      } else if (list != null && list.size() == 1) { //如果集合长度为1，则将元素取出作为结果返回
        value = list.get(0);
      }
    }
    return value;
  }
}
